<template>
  <a-form-model
    style="width:350px;margin:0 auto;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);border:1px solid #e8e8e8;"
    ref="ruleForm"
    :model="ruleForm"
    :rules="rules"
    v-bind="layout"
  >
    <a-divider>登录</a-divider>
    <a-form-model-item has-feedback label="账户" prop="username">
      <a-input v-model="ruleForm.username" type="text" autocomplete="off" />
    </a-form-model-item>
    <a-form-model-item has-feedback label="密码" prop="password">
      <a-input v-model="ruleForm.password" type="password" autocomplete="off" />
    </a-form-model-item>
    <a-form-model-item has-feedback label="验证码" prop="code">
      <a-input v-model="ruleForm.code" type="text" autocomplete="off" />
    </a-form-model-item>
    <a-form-model-item label="图形验证码">
      <img @click="CAPTCHA()" :src="captcha.src" width="150px" height="60px" />
    </a-form-model-item>
    <a-form-model-item :wrapper-col="{ span: 14, offset: 7 }">
      <a-button type="primary" @click="submitForm('ruleForm')">登录</a-button>
      <a-button style="margin-left: 10px" @click="resetForm('ruleForm')">重置</a-button>
    </a-form-model-item>
  </a-form-model>
</template>
<script>
import { mapState, mapActions } from "vuex";

export default {
  data() {
    return {
      ruleForm: {
        username: "",
        password: "",
        code: "",
        uuid: ""
      },
      rules: {
        username: {
          validator: (rule, value, callback) => {
            !value ? callback(new Error("请输入正确账户")) : callback();
          },
          trigger: "change"
        },
        password: {
          validator: (rule, value, callback) => {
            !value ? callback(new Error("请输入正确密码")) : callback();
          },
          trigger: "change"
        },
        code: {
          validator: (rule, value, callback) => {
            !value ? callback(new Error("请输入正确图形验证码")) : callback();
          },
          trigger: "change"
        }
      },
      layout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 }
      }
    };
  },
  computed: {
    ...mapState("authorization", ["captcha"])
  },
  created() {
    this.CAPTCHA();
  },
  methods: {
    ...mapActions("authorization", ["CAPTCHA", "LOGIN"]),
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.ruleForm.uuid=this.captcha.uuid
          this.LOGIN(this.ruleForm)
            .then(response => {
              this.$router.replace('index')
            })
            .catch(error => {
              this.$message.error(error);
            });
        } else {
          this.$message.error("提交失败");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>
